import axios from 'axios'; //引用axios
const baseURL = '/hb2/';
// axios 配置
axios.defaults.timeout = 10000;
axios.defaults.baseURL = baseURL; //这是调用数据接口
axios.defaults.withcRDentials = true; //让ajax携带cookie
// http request 拦截器，通过这个，我们就可以把Cookie传到后台
axios.interceptors.request.use(
  config => {
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);
// http response 拦截器
axios.interceptors.response.use(
  function(response) {
    //重定向到登录页面
    if (response.data.code === '401') {
      localStorage.clear();
      if (!response.data.url === '') {
        window.location.href = response.data.url; //这个url需要后端设置成公用的登录页url
      } else {
        window.location.href = response.data.msg;
      }
    }
    return response;
  },
  function(error) {
    return Promise.reject(error);
  }
);
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
export default axios;
export function request(url, data) {
  return new Promise(async resolve => {
    let responseType = 'json';
    let timeout = 10000;
    let headers = { 'Content-Type': 'application/json;charset=UTF-8' };
    let withCredentials = true;
    let method = 'post';
    let res = await axios({ baseURL, method, url, data, withCredentials, responseType, timeout, headers });
    resolve(res.data);
  });
}
export function axiosAll(list) {
  if (list instanceof Array) {
    return new Promise(resolve => {
      let axiosList = [];
      list.map(item => {
        axiosList.push(axios({ baseURL, method: 'post', url: item.url, data: item.data }));
      });
      Promise.all(axiosList).then(res => {
        let isOk = true;
        let resList = [];
        res.map(item => {
          if (item.status != 200) {
            isOk = false;
          }
          if (item.data.code != 200) {
            isOk = false;
          }
          resList.push(item.data);
        });
        if (isOk) {
          resolve(resList);
        }
      });
    });
  }
}
